package com.dlc.felear.xiaoensale.utils;

import android.util.Log;

import com.dlc.felear.xiaoensale.helper.JsonHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyArrList {
    private static final String TAG = "MyArrList";
    private int defaultSize = 5;
    private List<Integer> list;
    private boolean model = false;
    private int avg;
    private ExecutorService pool;


    public MyArrList(int defaultSize, boolean reject) {
        this.model = reject;
        this.defaultSize = defaultSize;
        list = new ArrayList<>(defaultSize);
        pool = Executors.newSingleThreadExecutor();
    }

    public void add(final int data) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                if (list == null) {
                    list = new ArrayList<>(defaultSize);
                }
                int size = list.size();
                if (size <= defaultSize) {
                    list.add(data);
                } else {
                    list.remove(0);
                    list.add(data);
                }
                handleData(list);
            }
        });
    }

    public List<Integer> getList() {
        return list;
    }

    /**
     * 获取平均值
     *
     * @return
     */
    public synchronized int getAvgValue() {
        return avg;
    }

    private synchronized void handleData(List<Integer> list) {
        int size = list.size();
        if (list.isEmpty()) {
            return;
        }
        if (size == 1) {
            avg = list.get(0);
            return;
        }
        //如果集合大于或者等于2个以上
        Collections.sort(list);
        Log.e("qindaji","1 size="+size+" list="+ JsonHelper.toJson(list));
        //去掉最小值
//        if (size > 3) {
//            if (model) {
//                list.remove(size - 1);
//            } else {
//                list.remove(0);
//            }
//        }
//        size = list.size();
        int temp = 0;
        for (Integer tt : list) {
            temp += tt;
        }
        avg = (temp / size);
        Log.e("qindaji","2 size="+size+" list="+ JsonHelper.toJson(list)+"  avg="+avg);

    }


    /**
     * 清除数据
     */
    public void claerData() {
        list.clear();
    }

    public boolean isEmpty() {
        return list.isEmpty();
    }


}
